package com.wangwenjun.concurrency.chapter14.reentrantlock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class UseReentrantLock1 {

    private static final ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {
        lock.lock();
        Thread t1 = new Thread(() -> {
            show02();
        });
        t1.start();

        Thread.sleep(1_000);

        t1.interrupt();
    }


    /**
     * lock.lock(); 不能被打断
     */
    private static void show01(){
        lock.lock();
        try{
            System.out.println("执行业务代码");
        }finally {
            lock.unlock();
        }
    }

    /**
     * lock.lockInterruptibly(); 在阻塞的过程中可以被外部线程打断
     */
    private static void show02(){
        try{
            lock.lockInterruptibly();
        } catch (InterruptedException e) {
            return;
        }

        try{
            System.out.println("do work");
        }finally {
            lock.unlock();
        }
    }

    /**
     * lock.tryLock() 尝试下获取锁,获取不到就走人从不停留
     */
    private static void show03(){
        if(lock.tryLock()){
            try{
                System.out.println("执行业务代码");
            }finally {
                lock.unlock();
            }
        }

    }

    private static void show04(){
        try {
            if(lock.tryLock(500, TimeUnit.MILLISECONDS)){
                try{
                    System.out.println("执行业务代码");
                }finally {
                    lock.unlock();
                }
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

    }

}
